const axios = require('axios');
const fs = require('fs'); 
const puppeteer = require('puppeteer');

const writeUrl = function(url, file){

    axios.get(url)
        .then(res => {
            const  data  = res.data;
            fs.writeFile(file, data, 'utf8', 
                // 写入文件后调用的回调函数
            function(err) {  
                    if (err) throw err; 
                    // 如果没有错误
                    console.log("Data is written to file successfully.") 
            });

            }
        )
        .catch(err => {
            console.log('Error: ', err.message);
        });


}

async function writePng (url, file){

    // (async () => {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(url, {waitUntil: 'networkidle2'});
        await autoScroll(page);
        await page.screenshot({path: file, fullPage: true});
      
        await browser.close();
    //   })();

}

async function writePdf(url, file){
    // (async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await await page.goto(url, {waitUntil: 'networkidle2'});
    await autoScroll(page);
    await page.pdf({path: file, format: 'A4'});
    await browser.close();
    // })();
}

async function getList(i_msgid, i_itemidx){
let url = 'https://mp.weixin.qq.com/mp/appmsgalbum?action=getalbum&__biz=MzkxNzM0MjYzNQ==&album_id=2454302204003237891&count=10&begin_msgid=' + i_msgid + '&begin_itemidx=' +
i_itemidx + '&uin=&key=&pass_ticket=&wxtoken=&devicetype=&clientversion=&__biz=MzkxNzM0MjYzNQ%3D%3D&appmsg_token=&x5=0&f=json'
console.log(url);
const res = await axios.get(url)
return res;

}

async function autoScroll(page) {
    return page.evaluate(() => {
        return new Promise((resolve, reject) => {
            //滚动的总高度
            var totalHeight = 0;
            //每次向下滚动的高度 100 px
            var distance = 100;
            var timer = setInterval(() => {
                //页面的高度 包含滚动高度
                var scrollHeight = document.body.scrollHeight;
                //滚动条向下滚动 distance
                window.scrollBy(0, distance);
                totalHeight += distance;
                //当滚动的总高度 大于 页面高度 说明滚到底了。也就是说到滚动条滚到底时，以上还会继续累加，直到超过页面高度
                if (totalHeight >= scrollHeight) {
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        })
    });
}

async function getArticals(i_msgid, i_itemidx){
    let res = '';
    let data  = '';
    let articles = '';
    let len = 10;
    let msgid = '';
    let itemidx = '';
    let articlelist = [];
    
    while(len == 10){
        res = await getList(msgid, itemidx);
        data  = res.data;
        if(data.getalbum_resp.article_list == undefined){
            len = 0;
        }else{
            articles = data.getalbum_resp.article_list;
            len = articles.length;
            if(Array.isArray(articles)){
                articlelist.push(...articles);
                articles.forEach(item => {
                    msgid = item.msgid;
                    itemidx = item.itemidx;
                });
            }else{
                articlelist.push(articles);
                console.log(JSON.stringify(articles));
                len = 0;
            }
        }
    }
    return articlelist;
}


// const processArticals = async function(articles){
//     console.log("显示article列表");
//     console.log(JSON.stringify(articles));
//     for(var item of articles){
//         let filename = item.pos_num + '.pdf';
//         await writePdf(item.url, filename);
//     }
// }

const processArticals = async function(articles){
    console.log("开始处理article列表");

    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    for(var item of articles){
        let filename = item.pos_num + '_' + item.title.replaceAll('/', '') + '.pdf';
        console.log("开始处理第", filename, "篇文章");
        await await page.goto(item.url, {waitUntil: 'networkidle2'});
        await autoScroll(page);
        await page.pdf({path: filename, format: 'A4'});
    }
    await browser.close();
}



const getWechat = async function(i_msgid, i_itemidx){
    const articlelist = await getArticals(i_msgid, i_itemidx);
    await processArticals(articlelist);
}


getWechat(2247487994, 1);
// writePdf('http://mp.weixin.qq.com/s?__biz=MzkxNzM0MjYzNQ==&mid=2247483709&idx=1&sn=a8cc37048c9a017595afe75aaa3caad0&chksm=c14351f9f634d8ef16a73e9dc4a18ff0df58f6f0428a30135fa5f78e3a62751e6a2cb8f0ffa3#rd', '1.pdf');
// writePng('http://mp.weixin.qq.com/s?__biz=MzkxNzM0MjYzNQ==&mid=2247483709&idx=1&sn=a8cc37048c9a017595afe75aaa3caad0&chksm=c14351f9f634d8ef16a73e9dc4a18ff0df58f6f0428a30135fa5f78e3a62751e6a2cb8f0ffa3#rd', '1.png');